<template>
  <div>
    <van-nav-bar
      :title="data.goods_name"
      left-text="返回"
      left-arrow
      @click-left="back">
      <template #right>
        <van-button icon="descending" type="info" round plain size="mini" color="#409efe" @click="downloadAllPhoto"></van-button>
      </template>
    </van-nav-bar>
    <van-notice-bar v-show="photoList.length === 0" color="#e6a23c" background="#fdf6ec" left-icon="info-o">
      此用户图库为空，请联系工作人员
    </van-notice-bar>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-skeleton
      style="margin-top:2rem"
      title
      animate
      :round="true"
      :row="14"
      :row-width="[300,280,300,200,0,300,280,300,200,0,300,280,300,200]"
      :loading="loading">
      <div v-for="(item,index) in timePhotoList" :key="index">
        <div>
          <van-divider content-position="left" :style="{ borderColor: '#fff' }" style="margin-left:-10%;">{{item.time}}</van-divider>
          <van-grid
            :column-num="3"
            :border="false"
            square>
            <van-grid-item
              v-for="(sonItem,sonIndex) in item.url"
              :key="sonIndex"
              @click.stop="imageLook(item.url,sonIndex)"
              >
              <van-swipe-cell>
                <van-image
                  width="3rem"
                  height="3rem"
                  :src="sonItem"
                  fit="cover"
                />
                <template #right>
                  <van-button square text="下载" type="info" style="height:100%"  color="#409efe" @click.stop="download(sonItem,sonIndex)"/>
                </template>
              </van-swipe-cell>
            </van-grid-item>
          </van-grid>
        </div>
      </div>
      </van-skeleton>
    </van-pull-refresh>
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}
export default {
  data() {
    return {
      id: '',
      data: {},
      datalist: [],
      isLoading: false,
      loading: false,
      // 图片列表
      photoList: [],
      // 时间线图片列表
      timePhotoList: [],
      // 全部图片
      allPic: []
    }
  },
  created() {
    var urlData = this.$route.query
    this.id = urlData.id
    this.getData()
  },
  mounted() {

  },
  methods: {
    // 下载全部图片
    downloadAllPhoto() {
      // console.log(this.urls, '=====urls')
      for (var i in this.datalist) {
        this.allPic.push(this.datalist[i].pics_big_url)
      }
      // console.log(this.allPic, '====allpics')
      var time = setTimeout(() => {
        this.handleBatchDownload()
        clearTimeout(time)
      }, 600)
    },
    handleBatchDownload() {
      const data = this.allPic // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
      const zip = new JSZip()
      const cache = {}
      const promises = []
      data.forEach(item => {
        const promise = getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
          const arrname = item.split('/')
          const filename = arrname[arrname.length - 1] // 获取文件名
          zip.file(filename, data, { binary: true }) // 逐个添加文件
          cache[filename] = data
        })
        promises.push(promise)
      })
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
          FileSaver.saveAs(content, this.data.goods_name + this.id + '.zip') // 利用file-saver保存文件
        })
      })
    },
    // 下拉刷新
    onRefresh() {
      var time = setTimeout(() => {
        this.$toast('刷新成功')
        this.isLoading = false
        this.photoList = []
        this.timePhotoList = []
        this.getData()
        clearTimeout(time)
      }, 1000)
    },
    // 图片下载
    download(url, index) {
      var num = index + 1
      var name = this.data.goods_name + num
      this.downloadIamge(url, name)
    },
    // 封装图片下载函数
    downloadIamge (imgsrc, name) { // 下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    imageLook(url, index) {
      ImagePreview({
        images: url,
        startPosition: index,
        closeable: true
        // showIndicators: true
      })
    },
    timeFilterP(value) {
      var date = new Date(value)
      var YY = date.getFullYear()
      var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
      var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
      return YY + '年' + MM + '月' + DD + '日'
    },
    handleArr(arr) {
      var narr = []
      // console.log(arr, '=======arrrrr')
      narr = arr.map(function(item, index, arr) {
        const i = arr.find(_item => item.time === _item.time)
        if (i !== item) {
          i.url.push(item.url)
          return undefined
        } else {
          i.url = [i.url]
          return i
        }
      }).filter(item => item !== undefined)
      // console.log(narr, '===narr')
      return narr
    },
    getData() {
      var _this = this
      this.loading = true
      this.$http.get(`goods/${this.id}`).then(res => {
        console.log(res.data.data, '===id')
        if (res.data.meta.status !== 200) return this.$toast.fail('数据获取失败！')
        this.data = res.data.data
        this.datalist = this.data.pics
        res.data.data.pics.forEach(e => {
          // console.log(e, '====e')
          var obj = {}
          obj.time = this.timeFilterP(e.add_time)
          obj.url = e.pics_big_url
          _this.photoList.push(obj)
          // console.log(obj)
          // console.log(_this.photoList, '=====goodIdList')
        })
        var time = setTimeout(() => {
          this.getTimePhotoList()
          clearTimeout(time)
        }, 3500)
      })
    },
    getTimePhotoList() {
      console.log(this.photoList, '====photo')
      this.timePhotoList = this.handleArr(this.photoList)
      console.log(this.timePhotoList, '=====goodIdList')
      if (this.timePhotoList.length !== 0) {
        this.loading = false
      }
    },
    back() {
      this.$router.push(`library?activeName=b`)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
